import wepy from 'wepy'
import tip from './tip'
import md5 from './md5';

const appid = "8251929704";
const secritkey = "rIhEvHZaEpZqfugwYGKaTKkCcNsMPIyb";
const Authorization = appid + '{|}' + md5.hex_md5(appid + secritkey);

// HTTP工具类
export default class Http {
	static async request (method, url, data) {
		let header = {}

		header.Authorization = Authorization;
		header.accessToken = wepy.getStorageSync('access_token');
		const param = {
			url: url,
			method: method,
			data: data,
			header: header,
		};
		tip.loading();
		let res = await wepy.request(param);

		if (this.isSuccess(res)) {
			tip.loaded();
			return res.data;
		} else {
			console.error(method, url, data, res);
			tip.loaded();
			throw this.requestException(res);
		}
	}

	/**
	 * 判断请求是否成功
	 */
	static isSuccess(res) {
		const wxCode = res.statusCode;
		// 微信请求错误
		if (wxCode !== 200) {
			return false;
		}
		const wxData = res.data;
		return !(wxData && wxData.code !== 0);
	}

	/**
	 * 异常
	 */
	static requestException(res) {
		const error = {};
		error.statusCode = res.statusCode;
		const wxData = res.data;
		const serverData = wxData.data;
		if (serverData) {
			error.serverCode = wxData.code;
			error.message = serverData.message;
			error.serverData = serverData;
		}
		return error;
	}

	static get (url, data) {
		return this.request('GET', url, data)
	}

	static put (url, data) {
		return this.request('PUT', url, data)
	}

	static post (url, data) {
		return this.request('POST', url, data)
	}

	static patch (url, data) {
		return this.request('PATCH', url, data)
	}

	static delete (url, data) {
		return this.request('DELETE', url, data)
	}
}